package jp.co.dailyReport.dailyReport.action;

import java.io.IOException;
import java.util.Vector;
import java.util.Calendar;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.DynaActionForm;
import jp.co.dailyReport.DataUnavailableException;
import jp.co.dailyReport.dailyReport.DailyReportWorkItem;
import jp.co.dailyReport.staff.Staff;
import jp.co.dailyReport.project.PjStaff;
import jp.co.dailyReport.project.PjStaffManager;
import jp.co.dailyReport.project.Project;
import jp.co.dailyReport.project.ProjectManager;
import jp.co.dailyReport.workItem.WorkItem;
import jp.co.dailyReport.workItem.WorkItemManager;
import jp.co.dailyReport.SystemCalendar;
import jp.co.dailyReport.Utilities;
import jp.co.dailyReport.dailyReport.DailyReport;
import jp.co.dailyReport.dailyReport.DailyReportManager;
import jp.co.dailyReport.dailyReport.DailyReportWorkItemManager;

/**
 * 日報登録の作業日入力ページのボタン（登録、削除）
 * が押されたときの処理を管理するクラスです。
 */
public class DailyReportAddAction extends Action {

	private static Logger log = Logger.getLogger(DailyReportAddAction.class);
	
	/**
	 * 日報登録の作業日入力ページのボタン（登録、削除）が押されたときの処理を実行します。<BR><BR>
	 * 「登録」ボタンが押された場合の処理：<BR>
	 * 作業日と社員IDから日報情報を取得し、日報情報があるならば、DynaActionFormオブジェクトの
	 * フィールドに設定します。<BR>
	 * 日報情報がないならば、社員IDから日報IDの最大値の日報情報を取得し、DynaActionFormオブジェクトの
	 * フィールドに設定します。<BR>
	 * 日報IDから日報作業項目情報を取得し、セッションに設定します。<BR>
	 * 日報作業項目IDから作業項目情報を取得し、セッションに設定します。<BR>
	 * 社員IDからプロジェクト参加社員情報を取得しした後、プロジェクトIDからプロジェクト情報を取得します。<BR>
	 * 取得したプロジェクト情報をセッションに設定します。<BR><BR>
	 * 「削除」ボタンが押された場合の処理：<BR>
	 * 作業日と社員IDから日報情報を取得し、日報情報があるならば、DynaActionFormオブジェクトの
	 * フィールドに設定します。<BR>
	 * 日報情報がないならば、リクエストにエラーメッセージが設定されます。
	 * 
	 * @param mapping このインスタンスを選択するために使用したActionMapping
	 * @param form 存在するならば、このリクエストのためのActionForm Bean
	 * @param request 処理しているHTTPリクエスト
	 * @param response 処理しているHTTPレスポンス
	 * @return ActionForwardインスタンス
	 * @throws IOException, ServletException
	 */
	public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {

		log.debug("DailyReportAddAction start");
		HttpSession session = request.getSession();
		Staff staff = (Staff)session.getAttribute("LoginStaff");
		DynaActionForm doDailyReportActionForm = (DynaActionForm)form;
		String target = null;
		Calendar workDate = Utilities.getCalendarDate(
						((Integer)doDailyReportActionForm.get("workDateY")).intValue(),
						((Integer)doDailyReportActionForm.get("workDateM")).intValue(),
						((Integer)doDailyReportActionForm.get("workDateD")).intValue());
		Calendar now = Calendar.getInstance();
		Calendar now2 = Utilities.getCalendarDate(now.get(Calendar.YEAR), now.get(Calendar.MONTH)+1, now.get(Calendar.DAY_OF_MONTH)+1);
		if(!now2.after(workDate)){
			return mapping.findForward("dateerror");
		}
		try {
			//作業日と社員ＩＤを引数にして日報データの取得
			DailyReport dailyReport = DailyReportManager.load(workDate,staff.getStaffId());
			if(request.getParameter("add") != null) {
				target = addDailyReport(doDailyReportActionForm,request,dailyReport,staff);
			}else if(request.getParameter("rm") != null) {
				target = rmDailyReport(doDailyReportActionForm,request,dailyReport,staff);
			}
		} catch(DataUnavailableException due) {
			log.error(due.getMessage());
		}
		log.debug("DailyReportAddAction end");
		return mapping.findForward(target);

	}

	//日報データの追加・更新
	private String addDailyReport(DynaActionForm doDailyReportActionForm, HttpServletRequest request,DailyReport dailyReport,Staff staff) {

		HttpSession session = request.getSession();
		log.debug("session.getId() = " + session.getId());
		session.removeAttribute("dailyReport");
		session.removeAttribute("dailyReportWorkItem");
		Vector workItemList = new Vector();
		Vector projectList = new Vector();
		Vector nonDisplayWorkItemList = new Vector();
		DailyReportWorkItem[] dailyReportWorkItem = null;
		Vector dailyReportWorkItemList = new Vector();

		try {
			if(dailyReport.getDailyReportId()==0){
				//社員ＩＤを引数にしてごく最近の日報データの取得
				dailyReport = DailyReportManager.load(DailyReportManager.loadMaxId(staff.getStaffId()));
				dailyReportWorkItem = DailyReportWorkItemManager.load(dailyReport.getDailyReportId());
				for(int i = 0; i < dailyReportWorkItem.length; i++) {
					WorkItem workItem = WorkItemManager.load(dailyReportWorkItem[i].getWorkItemId());
					//プロジェクトの参加ﾁｪｯｸ
					if(PjStaffManager.isExist(workItem.getProjectId(),staff.getStaffId())){
						//プロジェクトの存在ﾁｪｯｸ
						if(ProjectManager.isExist(workItem.getProjectId())){
							//プロジェクトの終了ﾁｪｯｸ
							if(!ProjectManager.load(workItem.getProjectId()).isStatusFlg()){
								workItemList.add(workItem);
								dailyReportWorkItemList.add(dailyReportWorkItem[i]);
							}
						}
					}
				}
				dailyReportWorkItem = (DailyReportWorkItem[])dailyReportWorkItemList.toArray(new DailyReportWorkItem[0]);
			}else{
				doDailyReportActionForm.set("dailyReportId", new Integer(dailyReport.getDailyReportId()));
				doDailyReportActionForm.set("comment", dailyReport.getComment());
				dailyReportWorkItem = DailyReportWorkItemManager.load(dailyReport.getDailyReportId());
				for(int i = 0; i < dailyReportWorkItem.length; i++) {
					WorkItem workItem = WorkItemManager.load(dailyReportWorkItem[i].getWorkItemId());
					workItemList.add(workItem);
				}
			}
			if(dailyReport.getDailyReportId()!=0) {
				doDailyReportActionForm.set("workingStartHoursH", new Integer(dailyReport.getWorkingStartHours().get(Calendar.HOUR_OF_DAY)));
				doDailyReportActionForm.set("workingStartHoursM", new Integer(dailyReport.getWorkingStartHours().get(Calendar.MINUTE)));
				doDailyReportActionForm.set("workingEndHoursH", new Integer(dailyReport.getWorkingEndHours().get(Calendar.HOUR_OF_DAY)));
				doDailyReportActionForm.set("workingEndHoursM", new Integer(dailyReport.getWorkingEndHours().get(Calendar.MINUTE)));
				doDailyReportActionForm.set("staffId", new Integer(dailyReport.getStaffId()));
				doDailyReportActionForm.set("workDetail", dailyReport.getWorkDetail());
				doDailyReportActionForm.set("problem", dailyReport.getProblem());
				doDailyReportActionForm.set("toDo", dailyReport.getToDo());
			}
			PjStaff pjStaff[] = PjStaffManager.getProjectId(staff.getStaffId());
			for(int i = 0; i < pjStaff.length; i++) {
				//プロジェクトの存在ﾁｪｯｸ
				if(ProjectManager.isExist(pjStaff[i].getProjectId())){
					Project project = ProjectManager.load(pjStaff[i].getProjectId());
					projectList.add(project);
					//プロジェクトの終了ﾁｪｯｸ
					if(!project.isStatusFlg()){
						WorkItem[] allWorkItem = WorkItemManager.load(pjStaff[i].getProjectId(),staff.getStaffId());
						for(int j = 0; j < allWorkItem.length; j++) {
							nonDisplayWorkItemList.add(allWorkItem[j]);
						}
					}
				}
			}
		} catch(DataUnavailableException due) {
			log.error(due.getMessage());
		}
		session.setAttribute("pjWorkItemList", new Vector());
		session.setAttribute("pjDailyReportWorkItemList", new Vector());
		if(dailyReportWorkItem!=null) session.setAttribute("dailyReportWorkItem", dailyReportWorkItem);
		session.setAttribute("workItemList", (WorkItem[])WorkItemManager.sortWorkItemList(workItemList).toArray(new WorkItem[0]));
		session.setAttribute("projectList", projectList);
		session.setAttribute("nonDisplayWorkItemList", (WorkItem[])WorkItemManager.sortWorkItemList(nonDisplayWorkItemList).toArray(new WorkItem[0]));
		request.setAttribute("systemCalendar", new SystemCalendar());
		return "add";
	}

	//日報データの削除
	private String rmDailyReport(DynaActionForm doDailyReportActionForm, HttpServletRequest request,DailyReport dailyReport,Staff staff) {

		ActionErrors errors = new ActionErrors();
		Vector workItemList = new Vector();
		int dailyReportId = dailyReport.getDailyReportId();
		if(dailyReportId == 0){
			errors.add("errors.rm.dailyReport.invalid",new ActionError("errors.rm.dailyReport.invalid"));
			saveErrors(request,errors);
			return "error";
		} else {
			doDailyReportActionForm.set("dailyReportId", new Integer(dailyReportId));
			doDailyReportActionForm.set("staffId", new Integer(dailyReport.getStaffId()));
			doDailyReportActionForm.set("workDateY", new Integer(dailyReport.getWorkDate().get(Calendar.YEAR)));
			doDailyReportActionForm.set("workDateM", new Integer(dailyReport.getWorkDate().get(Calendar.MONTH)+1));
			doDailyReportActionForm.set("workDateD", new Integer(dailyReport.getWorkDate().get(Calendar.DATE)));
			doDailyReportActionForm.set("workingStartHoursH", new Integer(dailyReport.getWorkingStartHours().get(Calendar.HOUR_OF_DAY)));
			doDailyReportActionForm.set("workingStartHoursM", new Integer(dailyReport.getWorkingStartHours().get(Calendar.MINUTE)));
			doDailyReportActionForm.set("workingEndHoursH", new Integer(dailyReport.getWorkingEndHours().get(Calendar.HOUR_OF_DAY)));
			doDailyReportActionForm.set("workingEndHoursM", new Integer(dailyReport.getWorkingEndHours().get(Calendar.MINUTE)));
			doDailyReportActionForm.set("totalWorkingHours", new Double(dailyReport.getTotalWorkingHours()));
			doDailyReportActionForm.set("workDetail", dailyReport.getWorkDetail());
			doDailyReportActionForm.set("problem", dailyReport.getProblem());
			doDailyReportActionForm.set("toDo", dailyReport.getToDo());
			doDailyReportActionForm.set("comment", dailyReport.getComment());
			try {
				DailyReportWorkItem[] dailyReportWorkItem = DailyReportWorkItemManager.load(dailyReportId);
				for(int i = 0; i < dailyReportWorkItem.length; i++) {
					workItemList.add(WorkItemManager.load(dailyReportWorkItem[i].getWorkItemId()));
				}
				request.setAttribute("dailyReportWorkItem",dailyReportWorkItem);
				request.setAttribute("staff",staff);
				request.setAttribute("workItemList",workItemList);
				request.setAttribute("projectList",ProjectManager.load());
			} catch(DataUnavailableException due) {
				log.error(due.getMessage());
			}
			return "rm";
		}
	}
}